﻿var PARAM_SEPARATOR = "."; //Ex: 123,456,789
var PARAM_FLOAT_SEPARATOR = ","; //Ex: 123.23
var groupNumberChar = '.';
var groupDecimalNumberChar = ',';

// Format number: Add separators into number. Ex: 123456789 -> 123,456,789 
function addSeparatorToNumber(val) {
    var tmp, iDigit, i, flg;

    val = "" + val;
    val = removeComma(val);
    if (parseInt(val, 10) < 0) {
        flg = "-";
        val = val.substring(1, val.length);
    }
    else {
        flg = "";
    }
    iDigit = (val.length - ((Math.ceil(val.length / 3) - 1) * 3)) - 1;
    tmp = "";
    for (i = 0; i < val.length; i++) {
        tmp = tmp + val.charAt(i);
        if ((i == iDigit) && (i != val.length - 1)) {
            tmp = tmp + PARAM_SEPARATOR;
            iDigit = iDigit + 3;
        }
    }
    tmp = flg + tmp;
    return tmp;
}
function CheckCGiaIsValid(value) {

    return CheckDouble(value, 1, 99999999999.99);

}
function GetDecimalCurrency(value) {
    var i = value.indexOf('.');
    if (i < 0)
        return value;
    var result = value.substring(0, i + 3);
    return ReplaceAllChar(result,".",",");
}
function formatNumberAutoSeparate(number) {
    number=ReplaceAllChar(number, ".", "");
        
    var num = removeComma(GetDecimalCurrency(number));
    var newNum = "";
    var newNum2 = "";
    var count = 0;

    //check for decimal number
    if (num.indexOf(groupDecimalNumberChar) != -1) { //number ends with a decimal point
        if (num.indexOf(groupDecimalNumberChar) == num.length - 1) {
            num += "";
        }
        if (num.indexOf(groupDecimalNumberChar) == num.length - 2) { //number ends with a single digit
            num += "";
        }
        var a = num.split(groupDecimalNumberChar);
        num = a[0]; //the part we will commify
        var end = a[1].substring(0, 2); //the decimal place we will ignore and add back later


    }
    else {
        var end = "";
    }
    //this loop actually adds the commas 
    for (var k = num.length - 1; k >= 0; k--) {
        var oneChar = num.charAt(k);
        if (count == 3) {
            newNum += groupNumberChar;
            newNum += oneChar;
            count = 1;
            continue;
        }
        else {
            newNum += oneChar;
            count++;
        }
    } //but now the string is reversed!

    //re-reverse the string
    for (var k = newNum.length - 1; k >= 0; k--) {
        var oneChar = newNum.charAt(k);
        newNum2 += oneChar;
    }

    // add dollar sign and decimal ending from above
    if (end.length > 0)
        newNum2 = newNum2 + "," + end;
    return newNum2;

}

// Remove separators formatted number.Ex: 123,456,789 -> 123456789 
function removeSeparatorFromNumber(val) {
    var tmp, idx, i;

    if (val != "") {
        tmp = "" + val;
        for (i = 0; i < tmp.length; i++) {
            idx = tmp.indexOf(PARAM_SEPARATOR);
            if (idx != -1) {
                tmp = tmp.substring(0, idx) + tmp.substring(idx + 1, tmp.length);
                i = i - 1;
            }
        }
        return tmp;
    } else {
        return 0;
    }
}

// Remove separators formatted number.Ex: 123.456.789 -> 123456789 
function removeSeparatorFromNumberFloat(val) {
    var tmp, idx, i;
    alert(val);
    if (val != "") {
        tmp = "" + val;
        for (i = 0; i < tmp.length; i++) {
            idx = tmp.indexOf(PARAM_FLOAT_SEPARATOR);
            if (idx != -1) {
                tmp = tmp.substring(0, idx) + tmp.substring(idx + 1, tmp.length);
                i = i - 1;
            }
        }
        return tmp;
    } else {
        return 0;
    }
}

// formatNumber(number, digits [, separator])
// Ex: If digits=3, 123.2, 3 -> 123.200, 123->123.000, 123.3456->123.345 (using lower round) 
// separator={true, false}
function formatNumber(number, digits, separator) {
    if (isNaN(number)) return "";
    var str = "" + roundEx(number * Math.pow(10, digits), 0, DEFAULT_ROUND_TYPE);
    while (str.length <= digits) { str = "0" + str; }
    var decpoint = str.length - digits;
    var intpart = str.substring(0, decpoint);
    var floatpart = str.substring(decpoint, str.length);
    var result = intpart + PARAM_FLOAT_SEPARATOR + floatpart;
    if (separator)
        result = addSeparatorToNumber(intpart) + PARAM_FLOAT_SEPARATOR + floatpart;
    return result;
}

//change separating sign in formated number. Ex: 123,456.123 -> 123.456,123
function changeSeparatorTypeInNumber(number) {
    var str = "";
    for (i = 0; i < number.length; i++) {
        if (number.charAt(i) == ',')
            str += '.';
        else if (number.charAt(i) == '.')
            str += ',';
        else
            str += number.charAt(i);
    }
    return str;
}
function removeComma(number) {
    var str = "";
    for (i = 0; i < number.length; i++) {
        if (number.charAt(i) == groupNumberChar)
            str += '';
        else
            str += number.charAt(i);
    }
    return str;
}

// Parse string value to int value. Return 0 if "value" is not number format.
// This function do the same thing as javascript:parseInt() function, except
// it resturn 0 instead of NaN.
function parseNumber(string, digits) {
    var result = roundEx(string, digits, DEFAULT_ROUND_TYPE);
    if (isNaN(result)) result = 0;
    return result;
}
//
// Add Functions in here
//
function blockNonNumbers2(obj, e, allowDecimal, allowNegative) {
    var key;
    var isCtrl = false;
    var keychar;
    var reg;

    if (window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    }
    else if (e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }

    if (isNaN(key)) return true;

    keychar = String.fromCharCode(key);
    //alert(keychar)
    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl) {
        return true;
    }

    reg = /\d/;
    // var isFirstN = allowNegative ? keychar == '.' && obj.value.indexOf('.') == -1 : false;
    // var isFirstD = allowDecimal ? keychar == ',' && obj.value.indexOf(',') == -1 : false;


    //return isFirstN || isFirstD || reg.test(keychar);
    return reg.test(keychar);

}
function convertMoney(input) {
    // return input;
    // alert('input');
    var v;
    var money = '';
    var kq = '';
    var kiemtra;
    var len;
    var j = 0;
    var arr;
    var arr2;
    var giatri;
    var giatri2 = '';
    arr2 = input.toString().split(',');

    if (arr2.length > 1) {
        giatri2 = arr2[1].toString();
        if (giatri2 != '') {
            var arrgiatri2 = new Array();
            arrgiatri2 = giatri2.split('.');
            if (arrgiatri2.length > 1)//loia bo dau cham
            {

                for (var k = 1; k < arrgiatri2.length; k++) {
                    //giatri2=giatri2.replace('.','');
                    giatri2 = ReplaceChar(giatri2, '.', '');
                }
            }


        }
        input = arr2[0].toString();
        if (input == '')
            input = '0';

    }
    //input=input.replace('.','');
    input = ReplaceChar(input, '.', '');
    if (input != '' && input != null) {

        arr = input.toString().split('.');
        if (arr.length > 1) {//alert(input);
            giatri = reconvertMoney(input).toString();
        }
        else {
            giatri = input.toString();
        }

        giatri = giatri.replace('.', ',');

        if (giatri != '' || giatri != 0) {
            kiemtra = giatri.substring(0, giatri.indexOf(','));

            if (kiemtra == '') {
                v = giatri;
            }
            else {
                v = kiemtra;
            }
            len = v.length;

            for (i = len; i >= 0; i--) {
                kq += v.substr(i, 1);
                if (j != 0 && j != len) {
                    if ((j) % 3 == 0) {
                        kq += '.';
                    }
                }
                j++;
            }

            for (i = 0; i <= kq.length; i++) {
                money += kq.substr(kq.length - i, 1);
            }

        }
    }
    else {
        money = '';
    }

    if (giatri2 != '') {
        if (money == '')
            money = '0';
        money += ',' + giatri2;
    }

    return money;
}
function ReplaceChar(value, oldChar, newChar) {
    if (value.indexOf(oldChar) > 0)
        value = value.replace(oldChar, newChar);
    return value;
}

function CheckCPhanTramIsValid(value) {

    return CheckDouble(value, 0, 100);

}
function ReplaceAllChar(value, oldChar, newChar) {

    var index = value.indexOf(oldChar);
    while (index > 0) {
        value = value.replace(oldChar, newChar);
        index = value.indexOf(oldChar);
    }
    return value;
}